// import { login, logout, getInfo } from '@/api/user'
import { loginwx, login, logout } from '@/api/base/index' // 使用得request util中使用得url得参数不同，在配置文件中设置了一个是基于mock 一个是基于服务器
import { ipdw2 } from '@/api/core/apiInfo'
import { getToken, setToken, removeToken, setJWT, setUserId, removeJWT, removeUserId } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  location: '',
  stateToken: null,
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  jwt: '',
  userid: ''
}

const mutations = {
  SET_LOCATION: (state, location) => {
    state.location = location
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_STATETOKEN: (state, token) => {
    state.stateToken = token
  },

  SET_JWT: (state, jwt) => {
    state.jwt = jwt
  },
  SET_USERID: (state, userid) => {
    state.userid = userid
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {

  async setJWT({ commit }, JWT) {
    commit('SET_JWT', JWT)
  },

  async setLocation({ commit }, userInfo) {
    await ipdw2().then(response => {
      console.log(response)
      // const { city } = response.result.ad_info
      const { city } = response.info
      console.log('setLocation', response)
      commit('SET_LOCATION', city)
    })
  },

  // user login   通过
  /*  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }, */

  login({ commit }, userInfo) {
    const { username, password } = userInfo
    // 用于处理异步操作，比如用户登录的请求。
    return new Promise((resolve, reject) => {
      console.log('进入state中 user得login')
      login({ username: username.trim(), password: password }).then(response => {
        console.log(response)
        if (response.state === 'success') {
          const { roles, name, avatar, introduction, userid } = response.tokenInfo
          commit('SET_USERID', userid)
          commit('SET_STATETOKEN', response.tokenInfo)
          commit('SET_JWT', response.token)

          // 将重要信息持久化
          setJWT(response.token)
          setUserId(userid)

          setToken(response.tokenInfo)
          resolve()// 用来表示异步操作成功并返回结果
          // 调用 resolve()，表示异步操作成功，整个 Promise 执行成功，之后的 then() 语句将会执行。
        } else {
          reject('登录失败')// 用来表示异步操作失败并返回错误。
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  login_wx({ commit }, userInfo) {
    const { username, password, openid } = userInfo
    // 用于处理异步操作，比如用户登录的请求。
    return new Promise((resolve, reject) => {
      console.log('进入state中 user得login')
      loginwx({ username: username.trim(), password: password, openid: openid.trim() }).then(response => {
        console.log(response)
        if (response.state === 'success') {
          const { roles, name, avatar, introduction, userid } = response.tokenInfo
          commit('SET_USERID', userid)
          commit('SET_STATETOKEN', response.tokenInfo)
          commit('SET_JWT', response.token)

          // 将重要信息持久化
          setJWT(response.token)
          setUserId(userid)

          setToken(response.tokenInfo)
          resolve()// 用来表示异步操作成功并返回结果
          // 调用 resolve()，表示异步操作成功，整个 Promise 执行成功，之后的 then() 语句将会执行。
        } else {
          reject('登录失败')// 用来表示异步操作失败并返回错误。
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      console.log('刷新后，getInfo,state', state)
      if (state.jwt) {
        console.log(state)
        if (state.stateToken) {
          const { roles, name, avatar, introduction, userid } = state.stateToken
          commit('SET_ROLES', roles)
          commit('SET_NAME', name)
          commit('SET_AVATAR', avatar)
          commit('SET_INTRODUCTION', introduction)
          resolve(state.stateToken)
        }
      } else {
        reject('未登录')
      }

      /* getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { roles, name, avatar, introduction } = data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        resolve(data)
      }).catch(error => {
        reject(error)
      }) */
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])

        commit('SET_USERID', '')
        commit('SET_STATETOKEN', null)
        commit('SET_JWT', '')

        removeToken()
        resetRouter()

        removeJWT()
        removeUserId()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])

      removeToken()
      removeJWT()
      removeUserId()

      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
